package com.derbtec.refale.transaction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.derbtec.refale.R;
import com.derbtec.refale.activities.AddEventActivity;
import com.derbtec.refale.models.Event;
import com.derbtec.refale.util.Session;

public class SetEventAsyncTask extends AsyncTask<String, Integer, Boolean> {
	
	private Event event;
	private Activity activity;
	private ProgressDialog pdia;
	
	public SetEventAsyncTask(Activity activity, Event event) {
		this.event = event;
		this.activity = activity;
	}
	
	protected void onPreExecute(){ 
		   super.onPreExecute();
		        pdia = new ProgressDialog(((AddEventActivity) activity).getParent());
		        pdia.setMessage("Saving...");
		        pdia.setTitle(R.string.newevent);
		        pdia.show();
		        //pdia.getWindow().setGravity(Gravity.CENTER);
		}
	
	protected Boolean doInBackground(String... params) {
		try {
			
			//Setup HttpConnectionsettings
			HttpParams httpparams = new BasicHttpParams();
			HttpProtocolParams.setVersion(httpparams, HttpVersion.HTTP_1_1);
			DefaultHttpClient client = new DefaultHttpClient(httpparams);
			HttpPost post = new HttpPost("http://derb.square7.ch/jsoneventadd.php");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			
			//Writing Cookie in header for authentication
			post.setHeader("Cookie", Session.getCookie());
			
			//generate JSON-Event-Object
			JSONObject jsonobject = new JSONObject();
			jsonobject.put("name", event.getName());
			jsonobject.put("place", event.getPlace());
			jsonobject.put("description", event.getDescription());
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
			jsonobject.put("startdate", sdf.format(event.getStartDate()));
			jsonobject.put("enddate", sdf.format(event.getEndDate()));
			
			//Creator
			//jsonobject.put("creatorid", event.getCreator().getId());
			
			//put object in array for syntax completion
			JSONArray jsonarray = new JSONArray();
			jsonarray.put(jsonobject);
			
			StringEntity entity = new StringEntity(jsonarray.toString());
			post.setEntity(entity);
			Log.d("AddEventJSONSENT", jsonarray.toString());
			//sending request and get response
			HttpResponse response = client.execute(post);
			
			Log.d("HTTPSTATUS", ""+response.getStatusLine().getStatusCode());
			
			if (response.getStatusLine().getStatusCode() == 200){

				InputStream is = response.getEntity().getContent();
				BufferedReader bfr = new BufferedReader(new InputStreamReader(is));
				String line = bfr.readLine();
				String newline;
				while ((newline = bfr.readLine()) != null) {
					line += (newline  + "\n");
				}
				Log.d("JSONresponse", line);
	
	  
	              
	                
	           
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
		
	}
	
	protected void onProgressUpdate(Integer... progress) {	    
	}
	
	protected void onPostExecute(Boolean result) {
		pdia.dismiss();
		((AddEventActivity)activity).reload();
		
		//((EventListViewActivity) activity).addElements(elementbuffer);
//		((EventListViewActivity) activity).updateData();
		
		
	}
}

